/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utilities;

import java.awt.Component;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import resource.Macro;

/**
 *
 * @author fangchengjia
 */
public class Helper {
    private static final String CONFIG_FILE = "configure";
    
    public static String readConfig(String keyword){
        String dir = "";
        try (BufferedReader br = new BufferedReader(
                new FileReader(CONFIG_FILE))){
            for(String line; (line = br.readLine()) != null;) {
                if (line.contains(keyword)){
                    dir = line.substring(keyword.length()+1);
                }
            }
            br.close();
        } catch (IOException ex) {
            Logger.getLogger(
                    Helper.class.getName()).log(Level.SEVERE, null, ex);
        }
        return dir;
    }
    
    private static void _create_table(
            ResultSet rs, 
            String table,
            String table_model[],
            javax.swing.JTable target_table){
        DefaultTableModel defaultModel = Helper.createTableModel(table_model);
        try {
            while(rs.next()){
                Object []obj = new Object[table_model.length];
                int i = 0;
                for (String s : table_model){
                    obj[i++] = Codecs.decode(rs.getString(s));
                }
                defaultModel.addRow(obj);
            }
            target_table.setModel(defaultModel);
        } catch (SQLException ex) {
            Logger.getLogger(table).log(Level.SEVERE, null, ex);
        }
    }

    public static DefaultTableModel createTableModel(String table[]){
        DefaultTableModel defaultModel = new DefaultTableModel();
	List<String> lList = Arrays.asList(table);
	Iterator<String> iterator = lList.iterator();
	while (iterator.hasNext()) {
            defaultModel.addColumn(iterator.next());
	}
        return defaultModel;
    }
        
    public static int confirmDelete(Component c, String name){
        int n = JOptionPane.showConfirmDialog(
            c,
            String.format("Do you want to delete %s?", name),
            "Confirm Delete",
            JOptionPane.YES_NO_OPTION);
        return n;
    }
    
    public static String encodeValues(String values[]){
        String formated = "";
        for (String s: values){
            formated += String.format("'%s',", Codecs.encode(s));
        }
        return formated.substring(0, formated.length()-1);
    }
    
    public static String encodeValues(String table[], String values[]){
        String formated = "";
        int index = 0;
        for (String s: values){
            formated += String.format(
                    "%s='%s',", 
                    table[index++], 
                    Codecs.encode(s));
        }
        return formated.substring(0, formated.length()-1);
    }
    
    public static String getDaysFromToday(int days){
        Calendar calender = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        calender.setTime(new Date());
        calender.add(Calendar.DATE, days);
        return dateFormat.format(calender.getTime());
    }
    
    public static String getToday(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        return dateFormat.format(date);
    }
    
    public static String generateID(DBConnector dbSession, String table){
        int i = 0;
        while (dbSession.check(table, 
                String.format("id='%s'",
                        Codecs.encode(String.format("%d", i))))){
            i++;
        }
        return String.format("%d", i);
    }
    
    public static void loadOptions(
            DBConnector dbSession, 
            String table, 
            String record, 
            javax.swing.JComboBox target){
        try {
            ResultSet rs = dbSession.load(table, record);
            while (rs.next()){
                target.addItem(Codecs.decode(rs.getString(record)));
            }
        } catch (SQLException ex) {
            Logger.getLogger(table).log(Level.SEVERE, null, ex);
        }
    }
    
    public static void refresh(
            DBConnector dbSession, 
            String table, 
            String table_model[],
            javax.swing.JTable target_table){
        ResultSet rs = dbSession.load(table);
        _create_table(rs, table, table_model, target_table);
    }
    
    public static void searchBy(
            DBConnector dbSession, 
            String table, 
            String table_model[],
            javax.swing.JTable target_table,
            String key, 
            String searchKey){
        ResultSet rs = dbSession.search(table, key, Codecs.encode(searchKey));
        _create_table(rs, table, table_model, target_table);
    }
    
    public static String searchOwnerAttributeByName(
            DBConnector dbSession,
            String table,
            String owner,
            String key){
        return Codecs.decode(dbSession.load(
                table,
                String.format("%s='%s'", Macro.MEMBERSHIP_NAME_L, owner),
                key));
    }
}
